package dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import model.Employee;

public class EmployeeDAO {
	private EntityManagerFactory entityManagerFactory;

	public void setEntityManagerFactory( EntityManagerFactory entityManagerFactory ) {
		this.entityManagerFactory = entityManagerFactory;
	}

	/**
	 * 
	 * @param employee
	 */
	public void insert(Employee employee) {
		if (employee == null) {
			return;
		}
		EntityManager em = entityManagerFactory.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			em.persist(employee);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			em.close();
		}
	}

	/**
	 * 
	 * @param employee
	 */
	public void delete(Employee employee) {
		if (employee == null) {
			return;
		}
		EntityManager em = entityManagerFactory.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			employee = em.merge(employee);
			em.remove(employee);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			em.close();
		}
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	public Employee findByID(int id) {
		EntityManager em = entityManagerFactory.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		Employee ret = null;
		try {
			tx.begin();
			ret = em.find(Employee.class, id);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			em.close();
		}
		
		return ret;
	}
}
